<template>
  <view class="app-container temp-password-page">
    <view class="main">

      <view class="body">
        <mescroll-body @init="mescrollInit" @down="downCallback" @up="upCallback" class="list-wrapper" :bottom="40">
          <view class="body-content">
            <view class="card" v-for="item in list" style="margin-bottom: 20rpx">
              <hxk-card :key="item.title" :class="{ 'expired': item.pwdState === '2' }">
                <template v-slot:header>
                  <view class="title">
                    {{ item.lockName }}
                  </view>
                </template>
                <template v-slot:body>
                  <view class="content">
                    <view class="text-item">
                      <text>密码：{{ item.password }}</text>
                    </view>
                    <view class="text-item">
                      <text>有效期至：{{ item.authEndTime }}</text>
                    </view>
                    <view class="text-item">
                      <text>创建时间：{{ item.authStartTime }}</text>
                    </view>
                  </view>
                </template>
              </hxk-card>
            </view>
          </view>
        </mescroll-body>
        <view class="footer" @click="show=true">
          <text>新增临时密码</text>
        </view>
      </view>


    </view>

    <u-popup :show="show" @close="close" @open="open">
      <view class="popup-content">
        <view class="title">新增临时密码</view>

        <u-cell-group>
          <u-cell title="智能锁" :isLink="true" arrow-direction="right" :value="form.lock"
                  @click="showLockPanel = true"></u-cell>
          <u-cell title="有效期" :isLink="true" arrow-direction="right" :value="form.validityPeriod"
                  @click="showValidityPeriodPanel = true"></u-cell>
        </u-cell-group>
        <view class="num">
          <text>智能锁本月临时密码剩余数量：{{ form.remainingCount }} （每月{{ MONTHLY_GENTMPPWD_TIMES() }}次）</text>
        </view>
        <view class="btns">
          <u-button type="primary" shape="circle"
                    :text="form.remainingCount > 0 ? '生成临时密码':'本月暂无临时密码次数'"
                    @click="generatePassword " color="#FF7947"
                    :disabled="form.remainingCount===0"></u-button>
        </view>
      </view>
    </u-popup>

    <!--有效期选择器-->
    <u-picker :show="showValidityPeriodPanel" :columns="validityPeriodOptions" @confirm="validityPeriodSelect"
              :immediate-change="true"
              @cancel="showValidityPeriodPanel=false"></u-picker>

    <!--智能锁选择器-->
    <u-picker :show="showLockPanel" :columns="lockOptions" @confirm="lockSelect" :immediate-change="true"
              key-name="lockName"
              @cancel="showLockPanel=false"></u-picker>

  </view>
</template>

<script>
import HxkCard from "@/components/hxk-card/index";
import {MONTHLY_GENTMPPWD_TIMES} from "@/components/app-constant";
import {tempPasswordList} from "@/api/manager/lock";
import constant from "@/utils/constant";
import storage from "@/utils/storage";
import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins";
import {lockList} from "@/api/manager/lock";
import {addTempPassword} from "@/api/manager/lock";
import {addMinutesToTime, extractMinutes, getCurrentFormattedTime} from "@/utils/common";

export default {
  mixins: [MescrollMixin],
  components: {
    HxkCard
  },
  data() {
    return {
      houseId: null,
      form: {
        lock: '',
        lockId: null,
        validityPeriod: '5分钟',
        remainingCount: 0
      },
      // 智能锁选择面板
      showLockPanel: false,
      // 有效期选择面板
      showValidityPeriodPanel: false,
      // 有效期选择options
      validityPeriodOptions: [
        ['5分钟', '10分钟', '30分钟', '60分钟', '90分钟']
      ],
      lockOptions: [[]],
      show: false,
      list: []
    };
  },
  created() {
    let room = storage.get(constant.room);
    this.houseId = room.houseId;
    this.getLockList(this.houseId)
  },
  methods: {
    getLockList(houseId) {
      lockList(houseId).then(res => {
        this.lockOptions[0].push(...res.data);
        console.log(this.lockOptions)
        // 默认选择第一个
        const defaultLock = this.lockOptions[0][0];
        this.form = {
          lock: defaultLock.lockName,
          lockId: defaultLock.lockId,
          validityPeriod: '5分钟',
          remainingCount: defaultLock.pwdMarginNumber
        }
      })
    },
    // 查询房间临时密码列表
    upCallback(page) {
      let room = storage.get(constant.room);
      this.houseId = room.houseId;
      const data = {
        "pageNum": page.num,
        "pageSize": page.size,
        "houseId": this.houseId
      }
      this.queryParams = {
        ...data
      }
      tempPasswordList(this.queryParams).then(res => {
        this.mescroll.endBySize(res.rows.length, res.total)
        if (page.num === 1) this.list = [];
        this.list = this.list.concat(res.rows);
      }).catch(() => {
        this.mescroll.endErr();
      })
    },
    MONTHLY_GENTMPPWD_TIMES() {
      return MONTHLY_GENTMPPWD_TIMES
    },
    validityPeriodSelect(e) {
      this.showValidityPeriodPanel = false
      this.form.validityPeriod = e.value[0]
    },
    lockSelect(e) {
      this.showLockPanel = false;
      const selectedLock = e.value[0]
      this.form = {
        lock: selectedLock.lockName,
        lockId: selectedLock.lockId,
        remainingCount: selectedLock.pwdMarginNumber,
        validityPeriod: '5分钟'
      }
    },
    close() {
      this.show = false
    },
    open() {
      this.show = true
    },
    generatePassword() {
      if (this.form.remainingCount >= 1) {
        const room = storage.get(constant.room);
        const startTime = getCurrentFormattedTime()
        const minutes = extractMinutes(this.form.validityPeriod)
        const data = {
          lockId: this.form.lockId,
          orderId: room.orderId,
          authStartTime: getCurrentFormattedTime(),
          authEndTime: addMinutesToTime(startTime, minutes)
        }
        addTempPassword(data).then(res => {
          this.$modal.msgSuccess("生成临时密码成功")
          this.form.remainingCount--;
          // 刷新
          this.mescroll.resetUpScroll()
        })
      }
      this.show = false;
    }
  },
}
</script>

<style lang="scss" scoped>
.temp-password-page {

  .main {


    .body {

      padding: 20rpx;

      .body-content {

        .content {
          display: flex;
          flex-direction: column;

          .text-item {
            display: flex;
            justify-content: space-between;
            padding: 8rpx 20rpx;
          }
        }
      }
    }

    .footer {
      position: fixed;
      left: 0;
      bottom: 0;
      width: 100%;
      background-color: #FF7947;
      color: #fff;
      padding: 10px;
      text-align: center;
      border-top: 1px solid #ccc;
      padding-bottom: calc(env(safe-area-inset-bottom) / 2);
    }
  }

  ::v-deep .expired {
    .card {
      background-color: #f8f8f8 !important;
    }
  }

  .popup-content {
    height: 400rpx;
    padding: 20rpx;

    .title {
      font-size: 32rpx;
      color: #333;
      margin-bottom: 20rpx;
    }

    .num {
      font-size: 28rpx;
      color: #666;
      margin: 20rpx 0;
    }

    .btns {

    }

  }
}

</style>